package com.i8office.android.zhihuixinwu.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseFragment;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.widget.MyWebView;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * Created by pc on 2018/7/7.
 */
@ActivityFragmentInject(
        contentViewId = R.layout.fragment_web
)
public class WebFragment extends BaseFragment {
    @BindView(R.id.webView)
    MyWebView webView;
    OnGetPageTitle onGetPageTitle;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if(context instanceof OnGetPageTitle){
            onGetPageTitle = (OnGetPageTitle) context;
        }
    }

    public static WebFragment newInstance(String url) {
        Bundle args = new Bundle();
        args.putString("url",url);
        WebFragment fragment = new WebFragment();
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    protected void initView(View rootView) {
        ButterKnife.bind(this, rootView);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setAppCacheEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.i("url",url);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if(onGetPageTitle!=null){
                    onGetPageTitle.onGetPageTitle(title);
                }
            }
        });
        webView.loadUrl(getArguments().getString("url"));
    }
    public interface OnGetPageTitle{
        void onGetPageTitle(String title);
    }
}
